﻿using Castle.Core.Smtp;
using Common;
using Common.Model;
using Common.Platform;
using Common.Utility;
using Microsoft.EntityFrameworkCore;
using Stylet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace AWSV2.ViewModels
{
    public class ReuploadAllProgressViewModel : Screen
    {

        private string _text = I18NService.Translate(LangKeys.请稍后);
        public string Text
        {
            get
            {
                return _text;
            }
            set
            {
                SetAndNotify(ref _text, value);
            }
        }

        private string _summaryText = $"{I18NService.Translate(LangKeys.成功)}:0 {I18NService.Translate(LangKeys.失败)}:0";
        public string SummaryText
        {
            get
            {
                return _summaryText;
            }
            set
            {
                SetAndNotify(ref _summaryText, value);
            }
        }

        private double _total = 100;
        public double Total
        {
            get
            {
                return _total;
            }
            set
            {
                SetAndNotify(ref _total, value);
            }
        }

        private double _current;
        public double Current
        {
            get
            {
                return _current;
            }
            set
            {
                SetAndNotify(ref _current, value);
            }
        }

        private List<Common.Models.WeighingRecord> _records;

        private int _success;
        private int _failure;

        private IWindowManager _windowManager;
        /// <summary>
        /// 创建窗体
        /// </summary>
        public ReuploadAllProgressViewModel(IWindowManager windowManager, List<Common.Models.WeighingRecord> records)
        {
            _windowManager = windowManager;
            _records = records;
            Total = _records.Count;

            var worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;

            var uploader = Common.Platform.PlatformManager.Instance.Current;

            var model = new CleanupConfig.ProgressReportModel();

            var channelNo = SettingsHelper.AWSV2Settings.Settings["platformChannel"]?.Value ?? string.Empty;

            var db = AJDatabaseService.GetDbContext();

            worker.DoWork += (s, e) =>
            {
                var index = 1;
                var state = 0;
                foreach (var item in _records)
                {
                    model.Current = index;
                    model.Text = I18NService.Translate(LangKeys.正在上传_0_, item.Bh);

                    if(uploader is PlatformBase platform)
                    {
                        try
                        {
                            var uploadTask = Task.Run(() =>
                            {
                                return platform.UploadWeighRecordAsync(new PlatformBase.UploadWeighRecordParams
                                {
                                    WeighRecord = item
                                });
                            });
                            uploadTask.Wait();
                            if (uploadTask.Result.Success)
                            {
                                var id = item.AutoNo;
                                db.WeighingRecords.Where(p => p.AutoNo == id)
                                .ExecuteUpdate(sp => sp.SetProperty(p => p.IsUpload, true));
                            }
                            state = 1;
                            Thread.Sleep(1000);
                        }
                        catch (Exception ex)
                        {
                            state = 0;
                            AJLog4NetLogger.Instance().Error($"{item.Bh}-{item.Ch} 上传数据失败: 平台:{platform.Name}", ex);
                        }
                    }
                    
                    Thread.Sleep(100);

                    worker.ReportProgress(state, model);
                    index++;
                }

                model.Text = I18NService.Translate(LangKeys.上传完毕);
                worker.ReportProgress(-1, model);
                e.Result = model;

            };

            worker.ProgressChanged += (s, e) =>
            {
                var m = e.UserState as CleanupConfig.ProgressReportModel;

                Text = m.Text;
                Current = m.Current;
                if (e.ProgressPercentage == 0)
                {
                    _failure += 1;
                }
                else if (e.ProgressPercentage == 1)
                {
                    _success += 1;
                }
                SummaryText = $"{I18NService.Translate(LangKeys.成功)}:{_success} {I18NService.Translate(LangKeys.失败)}:{_failure}";
                //Total = m.Total;
            };

            worker.RunWorkerCompleted += async (s, e) =>
            {
                var ret = e.Result as CleanupConfig.ProgressReportModel;
                Text = e.Error?.Message ?? ret.Text;

                db.Dispose();

                await Task.Delay(2500);

                this.RequestClose();

            };

            worker.RunWorkerAsync();
        }
    }
}
